<template>
    <div>
        <div class="tDsReportTable" ref="tDsReportTable">
            <vxe-table show-overflow :height="curHeight" row-id="id" :loading="loading1" :data="tableData1" ref="xTable">
                <!-- <vxe-table-column type="checkbox" width="60"></vxe-table-column> -->
                <!-- <vxe-table-column type="seq" title="序号" width="60"></vxe-table-column> -->
                <!-- <vxe-table-column field="name" title="Name" sortable></vxe-table-column> -->
                <!-- <vxe-table-column field="sex" title="Sex"></vxe-table-column>
            <vxe-table-column field="age" title="Age"></vxe-table-column>
            <vxe-table-column field="rate" title="Rate"></vxe-table-column> -->

                <vxe-table-column field="ac_name" title="账户名称" fixed> </vxe-table-column>
                <vxe-table-column field="a_u_name" title="用户名称"> </vxe-table-column>
                <vxe-table-column field="pay_type_d" title="支付方式"></vxe-table-column>
                <vxe-table-column field="pay_time" title="缴费时间" width="160"></vxe-table-column>
                <vxe-table-column field="pay_sum" title="缴费金额"></vxe-table-column>
                <vxe-table-column field="ac_sum" title="账户余额"></vxe-table-column>
                <vxe-table-column field="self_sum" title="自费水电余额"></vxe-table-column>
                <vxe-table-column field="free_sum" title="免费水电余额"></vxe-table-column>
                <vxe-table-column field="oper_type_d" title="充值类型"></vxe-table-column>
                <vxe-table-column field="u_name" title="操作人"></vxe-table-column>
                <vxe-table-column field="pay_guid" title="操作">
                    <template slot-scope="scope">
                        <a style="color: #2680fa" @click="print(scope.row)">{{ scope.row.pay_guid ? '打印' : '打印' }}</a>
                    </template>
                </vxe-table-column>
            </vxe-table>

            <vxe-pager
                :loading="loading1"
                :current-page="tablePage1.currentPage"
                :page-size="tablePage1.pageSize"
                :total="tablePage1.totalResult"
                :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Total', 'Sizes']"
                @page-change="handlePageChange1"
            >
            </vxe-pager>
        </div>

        <tDsReportPrint v-if="showPrint" :orderId="curItem.pay_guid" :time="curItem.pay_time" @close="showPrint = false"></tDsReportPrint>
    </div>
</template>

<script>
import {AjaxCommon} from '@/libs/apiCommon'
import {PopupCommon} from '@/libs/popupCommon'
import html2pdf from 'html2pdf.js'
import {Document, Packer, Paragraph, Table, TableRow, TableCell, TextRun} from 'docx'
import {saveAs} from 'file-saver'
import tDsReportPrint from '@/view/managementCenter/dataReportCenter/components/tDsReportPrint'
export default {
    name: 'tDsReportTable',
    components: {tDsReportPrint},
    data() {
        return {
            showPrint: false,
            curHeight: document.body.clientHeight - 562,
            params: {},
            loading1: false,
            tableData1: [],
            tablePage1: {
                currentPage: 1,
                pageSize: 10,
                totalResult: 0
            },
            curItem: {}
        }
    },
    computed: {},
    created() {},
    methods: {
        print(item) {
            this.curItem = item
            this.showPrint = true
        },
        exportExcel(type) {
            if (type == 'excel') {
                // 调用内置导出方法
                this.$refs.xTable.exportData({
                    filename: '交易明细统计报表', // 文件名
                    sheetName: '交易明细统计报表', // 工作表名称
                    type: 'xlsx', // 导出类型（xlsx/csv）
                    // 可选：自定义导出列
                    columns: [
                        {field: 'ac_name', title: '账户名称'},
                        {field: 'a_u_name', title: '用户名称'},
                        {field: 'pay_type_d', title: '支付方式'},
                        {field: 'pay_time', title: '缴费时间'},
                        {field: 'pay_sum', title: '缴费金额'},
                        {field: 'ac_sum', title: '账户余额'},
                        {field: 'self_sum', title: '自费水电余额'},
                        {field: 'free_sum', title: '免费水电余额'},
                        {field: 'oper_type_d', title: '充值类型'},
                        {field: 'u_name', title: '操作人'}
                    ]
                })
            } else if (type == 'pdf') {
                const content = this.$refs.tDsReportTable
                const opt = {
                    margin: 10,
                    filename: '交易明细统计.pdf',
                    image: {type: 'jpeg', quality: 0.98},
                    html2canvas: {scale: 2}, // 提升清晰度
                    jsPDF: {unit: 'mm', format: 'a4', orientation: 'portrait'}
                }
                // 执行导出
                html2pdf().set(opt).from(content).save()
            } else {
                // 1. 创建Word文档
                const doc = new Document({
                    creator: 'admin', // 显式指定 creator（可选，避免默认值 undefined）
                    title: '交易明细统计',
                    sections: [
                        // 必须是数组！
                        {
                            // 节的配置（包含子元素）
                            children: [
                                // 标题
                                new Paragraph({
                                    children: [new TextRun({text: '交易明细统计', bold: true, size: 24})],
                                    alignment: 'center'
                                }),
                                // // 总计信息
                                // new Paragraph(`总计金额：¥${this.totalAmount || 0}`),
                                // new Paragraph(`记录数：${this.tableData?.length || 0} 条`),
                                new Paragraph(''), // 空行
                                // 表格（明细数据）
                                new Table({
                                    rows: [
                                        // 表头行
                                        new TableRow({
                                            children: [
                                                new TableCell({children: [new Paragraph('账户名称')]}),
                                                new TableCell({children: [new Paragraph('用户名称')]}),
                                                new TableCell({children: [new Paragraph('支付方式')]}),
                                                new TableCell({children: [new Paragraph('缴费时间')]}),
                                                new TableCell({children: [new Paragraph('缴费金额')]}),
                                                new TableCell({children: [new Paragraph('账户余额')]}),
                                                new TableCell({children: [new Paragraph('自费水电余额')]}),
                                                new TableCell({children: [new Paragraph('免费水电余额')]}),
                                                new TableCell({children: [new Paragraph('充值类型')]}),
                                                new TableCell({children: [new Paragraph('操作人')]})
                                            ]
                                        }),
                                        // 数据行
                                        ...this.tableData1.map(
                                            (item) =>
                                                new TableRow({
                                                    children: [
                                                        new TableCell({children: [new Paragraph(item.ac_name)]}),
                                                        new TableCell({children: [new Paragraph(item.a_u_name)]}),
                                                        new TableCell({children: [new Paragraph(item.pay_type_d.toString())]}),
                                                        new TableCell({children: [new Paragraph(item.pay_time)]}),
                                                        new TableCell({children: [new Paragraph(item.pay_sum)]}),
                                                        new TableCell({children: [new Paragraph(item.ac_sum)]}),
                                                        new TableCell({children: [new Paragraph(item.self_sum.toString())]}),
                                                        new TableCell({children: [new Paragraph(item.free_sum)]}),
                                                        new TableCell({children: [new Paragraph(item.oper_type_d)]}),
                                                        new TableCell({children: [new Paragraph(item.u_name)]})
                                                    ]
                                                })
                                        )
                                    ]
                                }),
                                // 分页信息
                                new Paragraph(''),
                                new Paragraph(`当前页：${this.tablePage1?.currentPage || 1} / ${this.tablePage1?.pageSize || 1}`, {
                                    alignment: 'right'
                                })
                            ]
                        }
                    ]
                })

                // 5. 生成并导出Word
                Packer.toBlob(doc)
                    .then((blob) => {
                        saveAs(blob, '交易明细统计.docx')
                    })
                    .catch((err) => {
                        console.error('导出失败：', err)
                    })
            }
        },
        getAllData() {
            return this.tableData1 ?? []
        },
        async getData(params) {
            this.params = params
            this.loading1 = true
            const res = await AjaxCommon(`/api/Payment/GetPayInfoReport`, 'post', params)
            if (res?.data?.Code == 200) {
                const data = res?.data.Message
                this.$emit('footer', JSON.stringify(data.footer))
                this.tableData1 = data.rows?.map((t, i) => {
                    t.id = 'test__' + i
                    return t
                })
            } else {
                this.$emit('footer', JSON.stringify([]))
                this.tableData1 = []
            }
            this.loading1 = false
            this.tablePage1.totalResult = parseInt(res?.data.Message?.total ?? 0)
        },

        handlePageChange1({currentPage, pageSize}) {
            this.tablePage1.currentPage = currentPage
            this.tablePage1.pageSize = pageSize
            this.getData(this.params)
        }
    }
}
</script>

<style lang="scss" scoped>
</style>